﻿using System.Windows.Forms;
using System.Drawing;
using System;

namespace QAToolsAddin.GenericDialogs.Fields
{
    public class FieldList<T> : Field, IField
    {
        readonly ComboBox _control;
        private bool _mandatory;

        public FieldList(string name, string info, T[] items, object selection, bool mandatory, bool retore = false)
            : base(name, info, retore) {
            _control = new ComboBox {
                DropDownStyle = ComboBoxStyle.DropDownList,
                MaxDropDownItems = 25,
                Height = 19
            };
            //_control.DataSource = new BindingSource(items, null);
            _control.Items.AddRange((object[])(object)items);
            _control.DropDown += AdjustDropDownWidth_DropDown;
            if (selection is int)
                _control.SelectedIndex = (int)selection;
            else
                _control.SelectedItem = selection;
            _mandatory = mandatory;
        }

        private void AdjustDropDownWidth_DropDown(object sender, EventArgs e) {
            var senderComboBox = (ComboBox)sender;
            int width = senderComboBox.DropDownWidth;
            Graphics g = senderComboBox.CreateGraphics();
            Font font = senderComboBox.Font;
            int vertScrollBarWidth = (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
                    ? SystemInformation.VerticalScrollBarWidth : 0;
            foreach (var item in senderComboBox.Items) {
                int newWidth = (int)g.MeasureString(item.ToString(), font).Width;
                if (width < newWidth)
                    width = newWidth;
            }
            senderComboBox.DropDownWidth = width;
        }

        public override Control Control {
            get { return _control; }
        }

        public T Value {
            get { return (T)_control.SelectedItem; }
            set { _control.SelectedItem = value; }
        }

        object IField.Value {
            get { return Value; }
            set { Value = (T)value; }
        }

        public override bool Validate(out string errorMessage) {
            errorMessage = string.Empty;
            if (_mandatory && _control.SelectedIndex == -1) {
                errorMessage = "Selection is empty";
                return false;
            }
            return true;
        }

    }

}
